<template>
  <div>
    <Drawer
        title="分配角色菜单"
        :closable="true"
        :mask-closable="true"
        @on-close="closeDrawer"
        v-model="drawerFlag"
        width="400"
        :scrollable="true"
      >
        <Button size="small" type="primary" @click="saveMenu">保存</Button>&nbsp;
        <Button size="small" style="margin-left: 10px" @click="closeDrawer">关闭</Button>&nbsp;
        <Tooltip content="刷新" placement="right">
          <Button size="small" style="margin-left: 10px" icon="md-refresh" type="success" shape="circle" @click="initData(roleId)"></Button>
        </Tooltip>
        <Divider/>
        <Tree :data="menuData" show-checkbox multiple scrollable ref="menuTree"></Tree>
        <Spin size="large" fix v-if="spinShow"></Spin>
      </Drawer>
  </div>
</template>
<script>
import {
  getMenuDataByRoleId,
  getMenuDataAll,
  getMenuData,
  batchSaveMenuData  
} from '@/api/menu'
import * as ResponseStatus from '@/api/response-status'
import { localRead } from '@/libs/util'
export default {
  name: 'SysmenuAssignDrawer',
  props: {},
  data() {
    return {
      roleId: '',
      drawerFlag: false,
      spinShow: true,
      allMenuData: [],
      roleMenuData: [],
      userMenuData: [],
      menuData: [
        {
          title: this.$config.permissionTreeTitle,
          expand: true,
          children: []
        }
      ]
    }
  },
  mounted() {},
  methods: {
    /**
     * 初始化数据，请求后端数据
     * @param roleId 角色id
     */
    initData(roleId) {
      this.drawerFlag = true
      this.spinShow = true
      this.roleId = roleId
      // 获取所有的菜单
      getMenuDataAll()
        .then(res => {
          const data = res.data
          if (data.code === ResponseStatus.OK) {
            this.allMenuData = data.data.rows
            // 获取当前指定角色的菜单
            getMenuDataByRoleId(roleId)
              .then(res => {
                const data = res.data
                if (data.code === ResponseStatus.OK) {
                  this.roleMenuData = data.data.rows
                  getMenuData().then(userRes => {
                    const data = userRes.data
                    if (data.code === ResponseStatus.OK) {
                      this.userMenuData = data.data
                      this.initMenuData()
                    } else {
                      this.$Message.error(data.message)
                    }
                  }).catch(userErr => {
                    console.log('获取当前登入用户角色错误')
                  })
                } else {
                  this.$Message.error(data.message)
                }
              })
              .catch(err => {
                console.log('获取角色菜单错误')
                this.$Message.error(err)
              })
          } else {
            this.$Message.error(data.message)
          }
        })
        .catch(err => {
          console.log('获取所有菜单错误')
          this.$Message.error(err)
        })
    },
    /**
     * 初始化权限数据
     */
    initMenuData() {
      const flag = localRead('isSuperAdmin')
      let data = this.userMenuData
      if (flag) {
        data = this.allMenuData
      }
      this.menuData[0].children = this.filterMenuData(data)
      this.spinShow = false
    },
    /**
     * 过滤菜单数据，返回菜单需要的数据
     * @param {*} row 
     */
    filterMenuData (rows) {
      // 获取到所有一级菜单
      let oneLevelMenuArr = rows.filter((item) => {
        return item.sysMenuMenuLevel == 1
      })
      // 获取到所有二级菜单
      let twoLevelmenuArr = rows.filter((item) => {
        return item.sysMenuMenuLevel == 2
      })
      // 获取到所有三级菜单
      let threeLevelmenuArr = rows.filter((item) => {
        return item.sysMenuMenuLevel == 3
      })
      // 定义菜单数组
      let menuDataArr = []
      // 循环一级菜单
      oneLevelMenuArr.forEach(oneLevel => {
        const menuData = this.encapsulationData(oneLevel)
        let twoChildren = []
        let oneMenuId = oneLevel.sysMenuId
        // 循环二级菜单
        twoLevelmenuArr.forEach(twoLevel => {
          if (oneMenuId == twoLevel.sysMenuParentId) {
            const menuData = this.encapsulationData(twoLevel)
            let threeChildren = []
            let twoMenuId = twoLevel.sysMenuId
            // 循环三级菜单
            threeLevelmenuArr.forEach(threeLevel => {
              if (twoMenuId == threeLevel.sysMenuParentId) {
                const menuData = this.encapsulationData(threeLevel)
                threeChildren.push(menuData)
              }
            })
            if (threeChildren.length) {
              // 当前二级菜单有下级菜单
              menuData.checked = false
            }
            menuData.children = threeChildren
            twoChildren.push(menuData)
          }
        })
        if (twoChildren.length) {
          // 当前一级菜单有下级
          menuData.checked = false
        }
        menuData.children = twoChildren
        menuDataArr.push(menuData)
      })
      return menuDataArr
    },

    /**
     * 根据菜单数据封装成需要的菜单数据
     * @param {}} level 
     */
    encapsulationData (level) {
      let menuData = {}
      menuData.title = level.sysMenuMetaTitle
      menuData.expand = true
      menuData.sysMenuId = level.sysMenuId
      let check = false
      if (level.sysMenuMenuLevel != 1) {
        this.roleMenuData.forEach(menuItem => {
          if (menuItem.sysMenuId === level.sysMenuId) {
            // 该角色有该菜单
            check = true
          }
        })
      }
      
      menuData.checked = check
      return menuData
    },
    // 关闭权限配置
    closeDrawer() {
      this.drawerFlag = false
      this.menuData = [
        {
          title: this.$config.permissionTreeTitle,
          expand: true,
          children: []
        }
      ]
    },
    /**
     * 保存权限
     */
    saveMenu() {
      if (this.roleId === '') {
        this.$Message.error('请刷新页面重试')
        return
      }
      // var checkData = this.$refs.menuTree.data
      var checkData = this.$refs.menuTree.getCheckedAndIndeterminateNodes()
      var sysMenuIds = []
      console.log(checkData)
      checkData.forEach(root => {
        // 对所有选中和半选中的数据进行遍历，去除第一个
        if (root.nodeKey != 0) {
          sysMenuIds.push(root.sysMenuId)
        }
      })
      console.log(sysMenuIds)
      var params = [{
        roleId: this.roleId,
        sysMenuId: 0
      }]
      sysMenuIds.forEach(item => {
        params.push({
          roleId: this.roleId,
          sysMenuId: item
        })
      })
      batchSaveMenuData(params)
        .then(res => {
          const data = res.data
          if (data.code === ResponseStatus.OK) {
            this.$Message.info("保存成功")
            this.drawerFlag = false
          } else {
            this.$Message.error(data.message)
          }
        })
        .catch(err => {
          this.$Message.error(err)
        })
    }
  }
}
</script>
